package com.kx.yooli.kx.wechat.config.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author john_sqwen-childe.wen
 * @date 2024/3/28
 * @PROJECT_NAME wechat
 * @description create CorsFilter by john_sqwen
 * and CorsFilter value is
 */
@Component
public class CorsFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(CorsFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init filter start filterName value is {},context value is {}",filterConfig.getFilterName(),filterConfig.getServletContext());
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("doFilter   start {},{}",servletRequest,servletResponse);
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if ("OPTIONS".equals(((HttpServletRequest) servletRequest).getMethod())) {
            log.info("OPTIONS value is  {}",((HttpServletRequest) servletRequest).getMethod());
            servletResponse.getWriter().println("ok");
            return;
        }
        log.info("method param value is {}",((HttpServletRequest) servletRequest).getMethod());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("destroy filter start");
        Filter.super.destroy();
    }
}
